// 内联类型定义，避免导入问题
interface PatientDevice {
  deviceId: string;
  name: string;
  type: string;
  status: string;
  lastConnected: number;
  batteryLevel: number;
  firmwareVersion: string;
  sensors: string[];
  location: string;
  isActive: boolean;
}

interface RealTimeMonitoringData {
  patientId: string;
  deviceId: string;
  timestamp: number;
  vitalSigns: {
    heartRate: number;
    bloodPressure: {
      systolic: number;
      diastolic: number;
    };
    temperature: number;
  };
  movementData: {
    acceleration: number[];
    gyroscope: number[];
    orientation: number[];
    rangeOfMotion: number;
  };
  alerts: any[];
}

interface RehabilitationData {
  sessionId: string;
  patientId: string;
  startTime: number;
  endTime: number;
  deviceId: string;
  exercises: {
    name: string;
    duration: number;
    repetitions: number;
    rangeOfMotion: {
      min: number;
      max: number;
      average: number;
    };
    accuracy: number;
  }[];
  completionRate: number;
  feedback: string;
}

// 模拟枚举值
const DeviceStatus = {
  ONLINE: 'ONLINE'
};

const PatientDeviceType = {
  WEARABLE: 'WEARABLE',
  EXOSKELETON: 'EXOSKELETON',
  BRACE: 'BRACE'
};

const SensorType = {
  HEART_RATE: 'HEART_RATE',
  PRESSURE: 'PRESSURE',
  TEMPERATURE: 'TEMPERATURE',
  FLEX: 'FLEX',
  IMU: 'IMU'
};

// 模拟数据 - 患者设备列表
const mockDevices: PatientDevice[] = [
  {
    deviceId: 'wearable-001',
    name: '智能手表',
    type: PatientDeviceType.WEARABLE,
    status: DeviceStatus.ONLINE,
    lastConnected: Date.now(),
    batteryLevel: 85,
    firmwareVersion: 'v1.2.3',
    sensors: [SensorType.HEART_RATE, SensorType.PRESSURE, SensorType.TEMPERATURE],
    location: '手腕',
    isActive: true,
  },
  {
    deviceId: 'exo-001',
    name: '下肢外骨骼',
    type: PatientDeviceType.EXOSKELETON,
    status: DeviceStatus.ONLINE,
    lastConnected: Date.now() - 60000,
    batteryLevel: 70,
    firmwareVersion: 'v2.1.0',
    sensors: [SensorType.FLEX, SensorType.IMU, SensorType.PRESSURE],
    location: '下肢',
    isActive: true,
  },
  {
    deviceId: 'brace-001',
    name: '膝关节康复支具',
    type: PatientDeviceType.BRACE,
    status: DeviceStatus.ONLINE,
    lastConnected: Date.now() - 300000,
    batteryLevel: 92,
    firmwareVersion: 'v1.0.5',
    sensors: [SensorType.FLEX, SensorType.IMU],
    location: '右膝',
    isActive: true,
  },
];

// 模拟实时监控数据
const generateMockMonitoringData = (deviceId: string): RealTimeMonitoringData => {
  const heartRate = 60 + Math.floor(Math.random() * 30);
  const systolic = 110 + Math.floor(Math.random() * 20);
  const diastolic = 70 + Math.floor(Math.random() * 10);
  const temperature = 36.5 + (Math.random() * 0.8);
  
  return {
    patientId: 'patient-001',
    deviceId,
    timestamp: Date.now(),
    vitalSigns: {
      heartRate,
      bloodPressure: { systolic, diastolic },
      temperature: parseFloat(temperature.toFixed(1)),
    },
    movementData: {
      acceleration: [(Math.random() - 0.5) * 2, (Math.random() - 0.5) * 2, (Math.random() - 0.5) * 2],
      gyroscope: [(Math.random() - 0.5) * 180, (Math.random() - 0.5) * 180, (Math.random() - 0.5) * 180],
      orientation: [(Math.random() - 0.5) * 360, (Math.random() - 0.5) * 360, (Math.random() - 0.5) * 360],
      rangeOfMotion: 30 + Math.random() * 60,
    },
    alerts: [],
  };
};

// 模拟康复训练数据
const mockRehabilitationData: RehabilitationData = {
  sessionId: 'session-001',
  patientId: 'patient-001',
  startTime: Date.now() - 3600000,
  endTime: Date.now() - 3240000,
  deviceId: 'exo-001',
  exercises: [
    {
      name: '膝关节屈伸',
      duration: 600000,
      repetitions: 30,
      rangeOfMotion: {
        min: 15,
        max: 120,
        average: 75,
      },
      accuracy: 0.85,
    },
  ],
  completionRate: 0.95,
  feedback: '训练表现良好',
};

// IoT设备服务类
export class IoTService {
  async getPatientDevices(patientId: string): Promise<PatientDevice[]> {
    await new Promise(resolve => setTimeout(resolve, 300));
    return mockDevices;
  }

  async getDeviceRealTimeData(deviceId: string): Promise<RealTimeMonitoringData> {
    await new Promise(resolve => setTimeout(resolve, 200));
    return generateMockMonitoringData(deviceId);
  }

  async getRehabilitationRecords(patientId: string, deviceId?: string): Promise<RehabilitationData[]> {
    await new Promise(resolve => setTimeout(resolve, 400));
    return [mockRehabilitationData];
  }

  async sendDeviceCommand(deviceId: string, command: string): Promise<{ success: boolean; message: string }> {
    await new Promise(resolve => setTimeout(resolve, 300));
    return {
      success: true,
      message: `命令 ${command} 已发送`,
    };
  }

  subscribeToDeviceUpdates(deviceId: string, callback: (data: RealTimeMonitoringData) => void): () => void {
    const intervalId = setInterval(() => {
      callback(generateMockMonitoringData(deviceId));
    }, 5000);

    return () => clearInterval(intervalId);
  }
}

export const iotService = new IoTService();